package com.qf.controller;

import com.qf.entity.City;
import com.qf.entity.Hotal;
import com.qf.entity.R;
import com.qf.feign.CityFeign;
import com.qf.feign.HotalFeign;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.List;
import java.util.UUID;

@Controller
@RequestMapping("/system")
public class SystemController {

    @Autowired
    private CityFeign cityFeign;

    @Autowired
    private HotalFeign hotalFeign;

    String uploadPath = "C:\\worker\\img";

    /**
     * 城市列表 - 页面跳转
     * @return
     */
    @RequestMapping("/citylist")
    public String cityList(Model model){

        //调用城市服务
        R<List<City>> cityResult = cityFeign.list();
        if (cityResult.getCode() == R.Code.SUCCESS) {
            model.addAttribute("cityList", cityResult.getData());
        }
        return "citylist";
    }

    /**
     * 城市列表 - 返回json
     * @return
     */
    @RequestMapping("/citylistjson")
    @ResponseBody
    public List<City> cityListJson(){
        //调用城市服务
        R<List<City>> cityResult = cityFeign.list();
        return cityResult.getData();
    }

    /**
     * 新增城市
     * @return
     */
    @RequestMapping("/cityadd")
    public String cityAdd(City city){
        R<Boolean> result = cityFeign.insert(city);
        return "redirect:/system/citylist";
    }

    /**
     * 酒店列表
     * @return
     */
    @RequestMapping("/hotallist")
    public String hotalList(Model model){
        //获取酒店列表
        R<List<Hotal>> list = hotalFeign.list();
        model.addAttribute("hotals", list.getData());
        return "hotallist";
    }

    /**
     * 新增酒店
     * @return
     */
    @RequestMapping("/hotalinsert")
    public String hotalInsert(Hotal hotal, MultipartFile file){

        String outPath = uploadPath + "\\" + UUID.randomUUID().toString();

        //上传 - 分布式文件系统（阿里云SSO文件系统）
        try (
            InputStream in = file.getInputStream();
            OutputStream out = new FileOutputStream(outPath);
        ) {
            //文件拷贝
            IOUtils.copy(in, out);
        } catch (Exception e){
            e.printStackTrace();
        }

        //设置反斜杠
        outPath = outPath.replace("\\", "/");

        hotal.setHotalImage(outPath);
        //调用酒店服务保存酒店信息
        hotalFeign.insert(hotal);
        return "redirect:/system/hotallist";
    }
}
